package com.ls.lserp.modules.purchase.service;




import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ls.lserp.dbaccess.Entity.ContractProcessingDetailEntity;
import com.ls.lserp.dbaccess.Entity.ContractProcessingEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.modules.order.dao.AuditInfoDao;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.purchase.dao.PuttingContractDao;
import com.ls.lserp.modules.purchase.entity.PurchaseContract;
import com.ls.lserp.modules.purchase.entity.PuttingContract;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.sys.entity.Sequence;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.UserUtils;
@Service
@Transactional(readOnly = false)
public class PuttingContractService extends CrudService<PuttingContractDao,PuttingContract>{

	//合同
	 @Autowired
	    private PuttingContractDao puttingContractDao ;
	// 审核表
				@Autowired
				    private AuditInfoDao  auditInfoDao;

	    /**
		 * 查询父项
		 * @param page
		 * @param user
		 * @return
		 */
	    public Page<PuttingContract> findPuttingContractList(Page<PuttingContract> page, PuttingContract puttingContract) {
	        // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
	        //designOption.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a"));
	        // 设置分页参数
	    	puttingContract.setPage(page);
	        // 执行分页查询
	        page.setList(puttingContractDao.findList(puttingContract));
	        return page;
	    }
	    
	    /**
		 * 获取甲方信息     
		 * @param ognization
		 * @return
		 */
		public Ognization getPartyA(Ognization ognization) {
			
			return puttingContractDao.getPartyA(ognization);
		}
	    /**
		 * 查询一条外发合同信息
		 * 
		 * @param user
		 * @return
		 */
	    public PuttingContract getContract(PuttingContract puttingContract) {
	        
	        return puttingContractDao.get(puttingContract);
	        
	    }
	    /**
		 * ID查询一条数据
		 * 
		 * @param user
		 * @return
		 */
	    public PuttingContract findByID(Long id){
	    	
	    	return puttingContractDao.get(id);
	    	
	    }
	    
	    /**
		 * ID查询款式信息
		 * 
		 * @param user
		 * @return
		 */
	    public List<PuttingContract> findStyleByID(PuttingContract puttingContract) {
	        
	        return puttingContractDao.findStyleByID(puttingContract);
	        
	    }
	    
	    /**
		 * 新增/修改一条数据
		 * @param user
		 */
	    @Transactional(readOnly = false)
	    public void savePuttingContract(PuttingContract puttingContract) {
	    	// 判断新建编辑
	    		//若为null 执行插入语句（新建）
	    		if (puttingContract.getId()==null){
	    			// 编辑
	    			String shortName = puttingContract.getOgnizationShortNameB();
	    			StringBuilder conCode = new StringBuilder();
    				conCode.append("120");
    				conCode.append(shortName);
    				conCode.append(DateUtils.formatDate(new Date(), "yyyy"));
    				conCode.append("30");
    		        Sequence sequence=SequenceUtil.ognizationCode(conCode.toString(), "sequence_purchaseContact", 4);
    		        puttingContract.setContractProcessNO(sequence.getReturnCode());
    		        puttingContract.preInsert();
    		        puttingContract.setContractAuditStatus(ResourcesUtil.getConfig("audit_uncommit"));
    		        puttingContractDao.insert(puttingContract);
    		        if (puttingContract.getStyleList()!=null) {
	    				for (int i = 0; i < puttingContract.getStyleList().size(); i++) {
	    					PuttingContract puttingContract_T =  puttingContract.getStyleList().get(i);
							if (puttingContract_T.getStyleID()==0) {
								continue;
							}
							puttingContract_T.setId(puttingContract.getId());
							puttingContract_T.setContractProcessNO(puttingContract.getContractProcessNO());
							puttingContract_T.preInsert();
							puttingContractDao.insertDetail(puttingContract_T);
	    				}
					}
	    				
	    		}else{
	    			// 更新数据
	    			puttingContract.preInsert();
	    			puttingContractDao.update(puttingContract);
	    			puttingContractDao.deleteDetail(puttingContract);
	    			if (puttingContract.getStyleList()!=null) {
	    				for (int i = 0; i < puttingContract.getStyleList().size(); i++) {
	    					PuttingContract puttingContract_T =  puttingContract.getStyleList().get(i);
							if (puttingContract_T.getStyleID()==0) {
								continue;
							}
							puttingContract_T.setId(puttingContract.getId());
							puttingContract_T.setContractProcessNO(puttingContract.getContractProcessNO());
							puttingContract_T.preInsert();
							puttingContractDao.insertDetail(puttingContract_T);
	    				}
					}
	    		}			
	    }
	    /**
		 * 提交一条数据
		 * @param user
		 */
	    @Transactional(readOnly = false)
	    public void commitPuttingContract(PuttingContract puttingContract) {
	    	// 判断新建编辑
	    			// 更新数据
	    	puttingContract.preInsert();
	    	puttingContract.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_wait_accept"));
	    	puttingContractDao.commitUpdate(puttingContract);
	    }
	    /**
		 * 删除一条数据
		 * @param user
		 */
	    @Transactional(readOnly = false)
	    public void deletePuttingContract(PuttingContract puttingContract) {
	    	// 判断新建编辑
	    			// 更新数据
	    	puttingContract.preInsert();
	    	puttingContractDao.delete(puttingContract);
	    }
	    
	    /**
	     * @Title: findAuditList
	     * @Description: 查询所有履历
	     * @param @param auditInfo
	     * @param @return
	     * @return List<AuditInfo> 
	     * @throws
	     */
	   public AuditInfo findAuditInfo(AuditInfo auditInfo) {
		   AuditInfo audit = new AuditInfo();
		   audit.setAuditList(auditInfoDao.findAllList(auditInfo));
		   audit.setAuditStatus(auditInfoDao.findAuditAcceptCount(auditInfo));
	       // 执行查询
	       return audit;
	   }
	   /**
	    * @Title: getAuditResult
	    * @Description: 审核结果
	    * @param @param auditInfo
	    * @param @return
	    * @return 审核结果通过数
	    * @throws
	    */
	  
	  public long getAuditResult(AuditInfo auditInfo) {
		   
	      return auditInfoDao.findAuditAcceptCount(auditInfo);
	  }
	  
	  /**
		  * @Title: saveAudit
		  * @Description: 保存履历信息
		  * @param @param auditInfo
		  * @return void 
		  * @throws
		  */
		@Transactional(readOnly = false)
		public void saveAuditInfo(AuditInfo auditInfo,boolean isUpdateStatus) {
			
			 // 插入履历表
		     auditInfo.preInsert();
		     auditInfo.setAuditDate(new Date());
		     auditInfo.setAuditUserId(UserUtils.getUser().getId());
	         // 新建版本号赋值1
		     auditInfo.setVersion(1L);
		     auditInfoDao.insert(auditInfo);
		     
		     auditInfo.preUpdate();
		     if (auditInfo.getAuditResult()==0) {
		    	 auditInfo.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_no"));
			}else if (auditInfo.getAuditResult()==1) {
				auditInfo.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
				 //外发加工合同信息表数据更新
				 ContractProcessingEntity contractProcessingEntity = new ContractProcessingEntity();
				 //执行中
				 contractProcessingEntity.setContractStatus("CONTRACT_STAUS-EXECUTE");
				 contractProcessingEntity.setUpdateDateTime(auditInfo.getUpdateDate());
				 contractProcessingEntity.setUpdateUserId(auditInfo.getUpdateBy().getId());
				 contractProcessingEntity.setContractProcessId(auditInfo.getAuditRelateId());
				 puttingContractDao.updateProcessingContractStatus(contractProcessingEntity);
				 //外发加工合同信息明细表数据更新
				 ContractProcessingDetailEntity contractProcessingDetailEntity = new ContractProcessingDetailEntity();
				 //入库申请
				 contractProcessingDetailEntity.setContractStatus(Long.valueOf(2));
				 contractProcessingDetailEntity.setUpdateUserId(auditInfo.getUpdateBy().getId());
				 contractProcessingDetailEntity.setUpdateDateTime(auditInfo.getUpdateDate());
				 contractProcessingDetailEntity.setContractProcessId(auditInfo.getAuditRelateId());
				 puttingContractDao.updateProcessingDetailContractStatus(contractProcessingDetailEntity);
			}
		     
		     puttingContractDao.updateStatus(auditInfo);
		     
		}
		/**
		 * 导出外发加工合同
		 *
		 * @throws IOException
		 */
		public ExcelTemplate export(PuttingContract puttingContract, String tempFilePath) throws IOException {
			// 返回值
			ExcelTemplate handle = new ExcelTemplate();
			// 输出采购合同信息
			printPuttingContractInfoTemp(tempFilePath, puttingContract, handle);
			// 输出采购原辅料信息
			if (puttingContract.getStyleList() != null && puttingContract.getStyleList().size() > 0 ) {
				printPuttingContractListInfoTemp(tempFilePath, puttingContract.getStyleList(), handle);
			}
			return handle;

		}
		private void printPuttingContractInfoTemp(String tempFilePath, PuttingContract puttingContract, ExcelTemplate handle) throws IOException {
			List<String> dataCellDeclare = new ArrayList<String>();
			// 变量值
			Map<String, Object> dataMapResult = new HashMap<String, Object>();
			
			// 甲方公司
			dataCellDeclare.add("ognizationNameA");
			dataMapResult.put("ognizationNameA", puttingContract.getOgnizationNameA());
			// 乙方公司
			dataCellDeclare.add("ognizationNameB");
			dataMapResult.put("ognizationNameB", puttingContract.getOgnizationNameB());
			// 甲方住所地
			dataCellDeclare.add("ognizationAddressA");
			dataMapResult.put("ognizationAddressA", puttingContract.getOgnizationAddressA());
			// 乙方住所地
			dataCellDeclare.add("ognizationAddressB");
			dataMapResult.put("ognizationAddressB", puttingContract.getOgnizationAddressB());
			// 甲方法人代表
			dataCellDeclare.add("legalPersonA");
			dataMapResult.put("legalPersonA", puttingContract.getLegalPersonA());
			// 甲方主联系人
			dataCellDeclare.add("contactPersonA");
			dataMapResult.put("contactPersonA", puttingContract.getContactPersonA());
			// 乙方法人代表
			dataCellDeclare.add("legalPersonB");
			dataMapResult.put("legalPersonB", puttingContract.getLegalPersonB());
			// 乙方主联系人
			dataCellDeclare.add("contactPersonB");
			dataMapResult.put("contactPersonB", puttingContract.getContactPersonB());
			// 甲方联系电话
			dataCellDeclare.add("contactPhoneA");
			dataMapResult.put("contactPhoneA", puttingContract.getContactPhoneA());
			// 甲方传真号码
			dataCellDeclare.add("contactFaxA");
			dataMapResult.put("contactFaxA", puttingContract.getContactFaxA());
			// 乙方联系电话
			dataCellDeclare.add("contactPhoneB");
			dataMapResult.put("contactPhoneB", puttingContract.getContactPhoneB());
			// 乙方传真号码
			dataCellDeclare.add("contactFaxB");
			dataMapResult.put("contactFaxB", puttingContract.getContactFaxB());
			// 甲方电子邮箱
			dataCellDeclare.add("contactEmailA");
			dataMapResult.put("contactEmailA", puttingContract.getContactEmailA());
			// 乙方电子邮箱
			dataCellDeclare.add("contactEmailB");
			dataMapResult.put("contactEmailB", puttingContract.getContactEmailB());
			// 付款方式
			dataCellDeclare.add("paymentWay");
			dataMapResult.put("paymentWay", puttingContract.getPaymentWay());
			// 合同状态
			dataCellDeclare.add("contractStatus");
			dataMapResult.put("contractStatus", puttingContract.getContractStatus());
			// 特殊说明
			dataCellDeclare.add("specialExplain");
			dataMapResult.put("specialExplain", puttingContract.getSpecialExplain());
			// 外发加工数量
			dataCellDeclare.add("contractMaterialQuantity");
			dataMapResult.put("contractMaterialQuantity", puttingContract.getContractMaterialQuantity());
			// 外发加工金额
			dataCellDeclare.add("contractAmount");
			dataMapResult.put("contractAmount", puttingContract.getContractAmount());
			// 签订日期
			dataCellDeclare.add("contractDateTime");
			if ("".equals(puttingContract.getContractDateTime()) || puttingContract.getContractDateTime() == null) {
				dataMapResult.put("contractDateTime", puttingContract.getContractDateTime());
			} else {
				dataMapResult.put("contractDateTime", DateUtils.formatDate(puttingContract.getContractDateTime(), "yyyy-MM-dd"));
			}
			// 预计交货日期
			dataCellDeclare.add("contractDeliveryDate");
			if ("".equals(puttingContract.getContractDeliveryDate()) || puttingContract.getContractDeliveryDate() == null) {
				dataMapResult.put("contractDeliveryDate", puttingContract.getContractDeliveryDate());
			} else {
				dataMapResult.put("contractDeliveryDate", DateUtils.formatDate(puttingContract.getContractDeliveryDate(), "yyyy-MM-dd"));
			}
			// 创建人员
			dataCellDeclare.add("firstName");
			dataMapResult.put("firstName", puttingContract.getCreateBy().getFirstName());
			// 创建时间
			dataCellDeclare.add("createDate");
			if ("".equals(puttingContract.getCreateDate()) || puttingContract.getCreateDate() == null) {
				dataMapResult.put("createDate", puttingContract.getCreateDate());
			} else {
				dataMapResult.put("createDate", DateUtils.formatDate(puttingContract.getCreateDate(), "yyyy-MM-dd"));
			}
						
			// 向excel表输出
			handle.writeData(tempFilePath, dataCellDeclare, dataMapResult, 0);
		}
		private void printPuttingContractListInfoTemp(String tempFilePath, List<PuttingContract> styleList, ExcelTemplate handle) throws IOException {
			// 变量声明
			List<String> dataCellDeclare = new ArrayList<String>();
			// 变量值集合
			List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
			dataCellDeclare.add("styleCustomerNo");
			dataCellDeclare.add("styleCatgoryCD");
			dataCellDeclare.add("customerContractNO");
			dataCellDeclare.add("styleCustomerNameT");
			dataCellDeclare.add("indentQuantity");
			dataCellDeclare.add("contractQuantity");
			dataCellDeclare.add("contractProcessCost");
			dataCellDeclare.add("firstNameT");
			dataCellDeclare.add("createDateT");
			
			// 结果
			Map<String, Object> map;
			// 临时接收变量
			PuttingContract tempBean;
			for (int i = 0; i < styleList.size(); i++) {
				map = new HashMap<String, Object>();
				tempBean = styleList.get(i);
				
				// 款号/款式名称
				if ("".equals(tempBean.getStyleNameCN()) || tempBean.getStyleNameCN() == null) {
					map.put("styleCustomerNo", tempBean.getStyleCustomerNo());
				} else {
					map.put("styleCustomerNo", tempBean.getStyleCustomerNo()+"/"+tempBean.getStyleNameCN());
				}
				// 款式类别
				map.put("styleCatgoryCD", tempBean.getStyleCatgoryCD());
				// 合同订单号
				map.put("customerContractNO", tempBean.getCustomerContractNO());
				// 客户
				map.put("styleCustomerNameT", tempBean.getStyleCustomerName());
				// 订单数量
				map.put("indentQuantity", tempBean.getIndentQuantity());
				// 外发数量
				map.put("contractQuantity", tempBean.getContractQuantity());
				// 加工费
				map.put("contractProcessCost", tempBean.getContractProcessCost());
				// 创建人员
				map.put("firstNameT", tempBean.getCreateBy().getFirstName());
				// 创建时间
				if ("".equals(tempBean.getCreateDate()) || tempBean.getCreateDate() == null) {
					map.put("createDateT", tempBean.getCreateDate());
				} else {
					map.put("createDateT", DateUtils.formatDate(tempBean.getCreateDate(), "yyyy-MM-dd"));
				}
				
				dataList.add(map);
			}
			// 向excel表输出
			handle.writeListData(tempFilePath, dataCellDeclare, dataList, 0);
		}
}
